import React, { Component } from 'react'
import './index.scss'

//导入antd的导航栏组件
import { Toast } from 'antd-mobile'

//导入API优化组件
import { API } from '../../utils/api'

//导入导航栏组件
import NavHeader from '../../components/NavHeader'

//导入react-virtualized中的长列表组件,自动调宽组件
import { List, AutoSizer } from 'react-virtualized'

//导入Utils获取当前城市的函数
import { getCurrentCity } from '../../utils/index'

//每个城市标题高度
const TITLE_HEIGHT = 36
//每个城市的高度
const NAME_HEIGHT = 50
//四大热门城市(具有房源)
const HOUSE_CITY = ['北京', '上海', '广州', '深圳']

//格式化城市列表数据
const formatCityData = (list) => {
  //城市列表
  const cityList = {}
  //城市按照首字母分类
  list.forEach((item) => {
    //获取城市的首字母
    const index = item.short.substr(0, 1)
    if (cityList[index]) {
      //对应的index存在 向后插入数据
      cityList[index].push(item)
    } else {
      //对应的index不存在
      //1.创建对应的index
      //2.覆盖空数据
      cityList[index] = [item]
    }
  })

  //城市序号 城市首字母获取
  const cityIndex = Object.keys(cityList).sort()

  return {
    cityList,
    cityIndex,
  }
}

//格式化城市首字母数据
const formatCityIndex = (title) => {
  switch (title) {
    case '#':
      return '当前定位'
    case 'hot':
      return '热门城市'
    default:
      return title
  }
}

export default class CityList extends Component {
  constructor(props) {
    super(props)
    this.state = {
      //城市数据
      cityList: {},
      //城市索引
      cityIndex: [],
      //高亮索引值
      activeIndex: 0,
    }

    //创建城市列表ref
    this.cityListComponent = React.createRef()
  }

  //获取城市数据
  getCityList = async () => {
    //获取一级城市
    const res = await API.get('/area/city', {
      params: {
        level: 1,
      },
    })
    //格式化1级城市
    const { cityList, cityIndex } = formatCityData(res.data.body)
    //获取热门城市
    const hotRes = await API.get('/area/hot')
    //列表添加热门城市
    cityList['hot'] = hotRes.data.body
    //序号添加热门城市
    cityIndex.unshift('hot')
    //获取当前定位城市
    const currentCity = await getCurrentCity()
    //列表添加定位城市
    cityList['#'] = [currentCity]
    //序号添加定位城市
    cityIndex.unshift('#')
    //设置初始值
    this.setState({
      cityList,
      cityIndex,
    })
  }

  //渲染城市列表
  rowRenderer = ({
    key, // 唯一区别值
    index, // 索引号
    isScrolling, // 当前项是否滚动
    isVisible, // 当前项是可见
    style, // 每行的样式和位置
  }) => {
    const { cityIndex, cityList } = this.state
    //首字母的值
    const title = cityIndex[index]
    //返回每行渲染的格式
    return (
      <div key={key} style={style} className="city">
        <div className="title">{formatCityIndex(title)}</div>
        {cityList[title].map((item) => (
          <div
            className="name"
            key={item.value}
            onClick={() => this.changeCity(item)}
          >
            {item.label}
          </div>
        ))}
      </div>
    )
  }

  //动态计算每行的高度
  getRowHeight = ({ index }) => {
    const { cityList, cityIndex } = this.state
    //标题高度+城市数量*城市高度
    return TITLE_HEIGHT + NAME_HEIGHT * cityList[cityIndex[index]].length
  }

  //渲染城市索引列表
  renderCityIndex = () => {
    const { cityIndex, activeIndex } = this.state
    return cityIndex.map((item, index) => (
      <li
        className="city-index-item"
        key={item}
        onClick={() => {
          this.cityListComponent.current.scrollToRow(index)
        }}
      >
        <span className={activeIndex === index ? 'index-active' : ''}>
          {item === 'hot' ? '热' : item}
        </span>
      </li>
    ))
  }

  //右侧序号列高亮
  onRowsRendered = ({ startIndex }) => {
    const { activeIndex } = this.state
    if (startIndex !== activeIndex) {
      this.setState({
        activeIndex: startIndex,
      })
    }
  }

  //返回点击城市
  changeCity = ({ label, value }) => {
    if (HOUSE_CITY.indexOf(label) > -1) {
      localStorage.setItem('hkzf_city', JSON.stringify({ label, value }))
      this.props.history.go(-1)
    } else {
      Toast.info('该城市暂无房源', 1, null, false)
    }
  }

  async componentDidMount() {
    await this.getCityList()
    //提前计算所有行的行高 提高跳转的精确性
    this.cityListComponent.current.measureAllRows()
  }

  render() {
    return (
      <div className="citylist">
        {/* 导航栏 */}
        <NavHeader title="城市选择"></NavHeader>
        {/* 城市列表 */}
        <AutoSizer>
          {({ width, height }) => (
            <List
              width={width}
              height={height}
              rowCount={this.state.cityIndex.length}
              rowHeight={this.getRowHeight}
              rowRenderer={this.rowRenderer}
              onRowsRendered={this.onRowsRendered}
              ref={this.cityListComponent}
              scrollToAlignment="start"
            />
          )}
        </AutoSizer>
        {/* 右侧索引列表 */}
        <ul className="city-index">{this.renderCityIndex()}</ul>
      </div>
    )
  }
}
